<?php
include("../../Connections/connect_admin.php");
if($_GET["task"]=="Search")
{
	$parentID=$_GET["parentID"];
	$query="select * from topic where IsDeleted = 0 and ParentID=".$parentID." order by OrderIndex";
	$result=mysql_query($query);
	$response=array();
	$i=0;
	while($row=mysql_fetch_assoc($result))
	{
		$item=array(
						'id'=>$row["TopicID"],
						'name'=>$row["TopicName"],
						'order'=>$row["OrderIndex"],
						'desc'=>$row["Description"],
						'_link'=>$row["Link"],
						'iswrite'=>$row["IsAllowWriteNews"],
						
						);
		$response[$i]=$item;
		$i++;
	}
	echo json_encode($response);
}
else if($_GET["task"]=="Add")
{
	//$topicID=intval($_GET["topicID"]);
	$name=$_GET["txtName"];
	$desc=$_GET["txtDescription"];
	$link=$_GET["txtLink"];
	$parentID=intval($_GET["Parent"]);
	$isallow=1;
	if($_GET["IsCreateNews"]!="1")
	{
		$isallow=0;
	}
	$order=mysql_num_rows(mysql_query("select * from topic where IsDeleted=0 and ParentID=$parentID"));
	$query="INSERT INTO topic(TopicName,Description,Link,ParentID,OrderIndex,IsAllowWriteNews) VALUES('$name','$desc','$link',$parentID,$order,$isallow)";
	if(mysql_query($query))
	{
		header('location:../Topic.php?e=0');
		
	}
	else
	{
		header('location:../Topic.php?e=1');
		
	}
}
else if($_GET["task"]=="delete")
{
	$topicID=intval($_GET["topicID"]);
	$deleteduser=$_GET["deleteduser"];
	$query="UPDATE `topic` SET IsDeleted = 1,DeletedDate = NOW(),DeletedUser = '$deleteduser' WHERE TopicID ='".$topicID."'";
	$result=mysql_query($query);
	$response=array();
	
		 $response = array(
        'ok' => true, 
        'msg' => "Xóa chuyên mục thành công");		
	
	echo json_encode($response);
}
else  if($_GET["task"]=="Update")
{
	$topicID=intval($_GET["topicID"]);
	$name=$_GET["txtName"];
	$desc=$_GET["txtDescription"];
	$link=$_GET["txtLink"];
	$parentID=intval($_GET["Parent"]);
	$isallow=1;
	if($_GET["IsCreateNews"]!="1")
	{
		$isallow=0;
	}
	
	$query="UPDATE topic SET TopicName = '$name',Description = '$desc',Link = '$link',ParentID = $parentID, IsAllowWriteNews = $isallow WHERE TopicID=$topicID";
	if(mysql_query($query))
	{
		header('location:../Topic.php?e=2');
		
	}
	else
	{
		header('location:../Topic.php?e=3');
		
	}
 }
 else  if($_GET["task"]=="UpdateOrder")
{	
	$link=$_GET["orderList"];
	$list=explode(',',$link);
	$flag=0;
	for($i=0;$i<count($list);$i++)
	{
		if($list[$i]!='')
		{
			$query="UPDATE topic SET OrderIndex=$i WHERE TopicID=".intval($list[$i]);
			if(mysql_query($query))
			{
				$response = array(
				'ok' => true, 
				'msg' => "Cập nhật thứ tự thành công");			
			}
			else
			{
				$response = array(
				'ok' => true, 
				'msg' => "Cập nhật thứ tự thất bại");	
			}
		}
	}
	echo json_encode($response);
	
 }
?>